// miniprogram/pages/index/index.js
const db = wx.cloud.database()
const userInfo = db.collection('userInfo')
const queueInfo = db.collection('queueInfo')
const _ = db.command
const app = getApp()
const util = require('../../utils/util.js')
Page({

   /**
    * 页面的初始数据
    */
   data: {
      queue_name:"新媒体面试",
      state:"排队中",
      queue_queuer:[],
      dialog_show:false,
      first_time:false
   },
   /**
     * @todo 结束队伍
     */
   cancel_queue(event){
      wx.showToast({
        title: '功能待完善',
      })
      console.log(event)
   },
   onDialog(){
      this.setData({ dialog_show: true });
   },
   onClose() {
      this.setData({ dialog_show: false });
    },
   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
      console.log(wx.getLaunchOptionsSync().query.queue_id)
      if (wx.getLaunchOptionsSync().query.queue_id != undefined) {
          wx.showLoading({
              title: '正在加载数据',
              mask: true
          })
          let flag = 0
          let data = []
          wx.cloud.callFunction({
              name: 'getOpenid',
              complete: res => {
                  // console.log(res.result)
                  const openid = res.result
                  userInfo.where({
                      _openid: res.result
                  }).count().then(res => {
                      const queue_id = wx.getLaunchOptionsSync().query.queue_id
                      queueInfo.doc(queue_id).get().then(res => {
                        console.log(res.data.queuer_list)
                          for (let i = 0; i < res.data.queuer_list.length; i++) {
                           // console.log(res.data.queuer_list[i]._openid)
                              if (res.data.queuer_list[i]._openid == openid) {
                                 flag = 1
                              }
                          }
                          if (flag == 0) {
                              let start_time = util.formatTime(new Date())
                              data = {
                                  _id: queue_id,
                                  _openid:openid,
                                  queue_title: res.data.title,
                                  state: "排队中",
                                  code_num: res.data.code_num ,
                                  start_time: start_time,
                                  queue_length: res.data.queue_length + 1,
                                  rank: res.data.queuer_list.length + 1
                              }
                              app.globalData.openid = openid
                              if (res.total == 0) {
                                  userInfo.add({
                                      data: {
                                          queuer: [].push(data),
                                          leader: []
                                      }
                                  }).then(res => {
                                      console.log(res)
                                  }).catch(err => {
                                      console.log(err)
                                  })
                              } else {
                                  console.log(data)
                                  userInfo.where({
                                      _openid: app.globalData.openid
                                  }).get().then(res => {
                                    //   console.log(res.data[0]._id)
                                      userInfo.doc(res.data[0]._id).update({
                                          data: {
                                              queuer: _.push(data)
                                          }
                                      })
                                  })
                              }
                          }
                      }).then(res => {
                          if (flag == 0) {
                              queueInfo.doc(queue_id).update({
                                  data: {
                                    queue_length:_.inc(1),
                                    queuer_list: _.push(data)
                                  }
                              })
                          }
                          userInfo.where({
                              _openid: openid
                          }).get().then(res => {
                              console.log(res.data[0])
                              app.globalData.userInfo = res.data[0]
                              this.setData({
                                  queue_queuer: res.data[0].queuer,
                                  first_time:false
                              })
                              this.onShow()
                              wx.hideLoading()
                          }).catch(err => {
                              console.log(err)
                          })
                      })
                  })
              }
          })
      }
  },

   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function () {

   },

   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function () {
      wx.showLoading({
         title: '正在刷新数据',
         mask:true
         })
      wx.cloud.callFunction({
         name: 'getOpenid',
         complete: res => {
            // console.log(res.result)
            const openid = res.result
            userInfo.where({
               _openid: res.result
            }).count().then(res => {
               app.globalData.openid = openid
               if (res.total == 0) {
                  userInfo.add({
                     data:{
                        queuer:[],
                        leader:[]
                     }
                  }).then(res=>{
                     console.log(res)
                  }).catch(err=>{
                     console.log(err)
                  })
               } else {
                     userInfo.where({
                        _openid: openid
                     }).get().then(res => {
                        console.log(res.data[0])
                        app.globalData.userInfo = res.data[0]
                        this.setData({
                           queue_queuer:res.data[0].queuer
                        })
                        wx.hideLoading()
                     }).catch(err=>{
                        console.log(err)
                     })
               }
            });
         }
      })
   },
   

   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide: function () {

   },

   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function () {

   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {

   },

   /**
    * 页面上拉触底事件的处理函数
    */
   onReachBottom: function () {

   },

   /**
    * 用户点击右上角分享
    */
   onShareAppMessage: function () {

   }
})